package com.tdf.lolpanel.utils;

import com.tdf.lolpanel.constant.MsgConstant;
import com.tdf.lolpanel.result.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获业务异常
     */
    @ExceptionHandler
    public Response exceptionHandler(BaseException e) {
        log.error("异常信息: {}", e.getMessage());
        return Response.error(e.getMessage());
    }
    @ExceptionHandler
    public Response exceptionHandler(IllegalStateException e) {
        log.error("验证异常: {}", e.getMessage());
        return Response.error(e.getMessage());
    }

    /**
     * 数据库操作异常
     */
    @ExceptionHandler
    public Response exceptionHandler(SQLException e) {
        String msg = e.getMessage();
        log.error("数据库错误：{}", msg);
        // 重复输入(这里不先查是因为查完再写会导致效率低)
        // exp: Duplicate entry '蟹老板test' for key 'user.username_UNIQUE'
        if(msg.contains("Duplicate entry")) {
            String[] split = msg.split(" ");
            String username = split[2];
            String errMsg = username + MsgConstant.ALREADY_EXISTS;
            return Response.error(errMsg);
        }
//        return Response.error(e.getMessage());
        return Response.error(MsgConstant.UNKNOWN_ERROR);
    }
}
